package cn.qiyu5522.security;

import cn.qiyu5522.domain.entity.ResponseResult;
import cn.qiyu5522.enums.AppHttpCodeEnum;
import cn.qiyu5522.utils.WebUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: AuthenticationEntryPointImpl
 * Package: cn.qiyu5522.handlers.security
 * Description:  认证失败处理器
 *
 * @Author: Tonkey
 * @Create：2024/4/12-15:00
 * @Version: v1.0
 */

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Resource
    private ObjectMapper objectMapper;
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        authException.printStackTrace();
//        InsufficientAuthenticationException
//        BadCredentialsException
        ResponseResult responseResult = null;
        if( authException instanceof BadCredentialsException){
            responseResult  = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }else if(authException instanceof InsufficientAuthenticationException){
            responseResult  = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else{
            responseResult  = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证或授权失败");
        }
        // 转化为JSON
        String json = objectMapper.writeValueAsString(responseResult);
        // 使用包装类返回给前端
        WebUtils.renderString(response,json);

    }
}
